#include <QGraphicsDropShadowEffect>
#include <QTimer>
#include <QRandomGenerator>
#include <QPushButton>
#include <QHBoxLayout>
#include <QLabel>
#include "vocabwordspage.h"
#include "ui_vocabwordspage.h"
#include "util/messagebox.h"
#include "util/localwordmanager.h"

namespace WordMemory
{
    VocabWordsPage::VocabWordsPage(const Vocabulary &vocab, QWidget *parent)
        : QWidget(parent)
        , ui(new Ui::VocabularyWordsPage)
        , serverhelper(new ServerHelper(this))
        , vocabulary(vocab)
        , currentDictationIndex(-1)
        , dictationDialog(new DictationDialog(this))
    {
        ui->setupUi(this);
        setupStyles();
        setupConnections();
        refreshWords();
    }

    VocabWordsPage::~VocabWordsPage()
    {

        dictationDialog->deleteLater();
        delete ui;
    }

    void VocabWordsPage::setupStyles()
    {
        QGraphicsDropShadowEffect *wordsShadow = new QGraphicsDropShadowEffect(this);
        wordsShadow->setBlurRadius(12);
        wordsShadow->setXOffset(0);
        wordsShadow->setYOffset(4);
        wordsShadow->setColor(QColor(0, 0, 0, 0.1 * 255));
        ui->wordsCardWidget->setGraphicsEffect(wordsShadow);

        // 返回按钮样式
        QString commonButtonStyle = R"(
            QPushButton { font-family: "Microsoft YaHei"; font-size: 15px; padding: 8px 12px; background-color: #1890ff; color: #ffffff; border-radius: 5px; border: none; }
            QPushButton:hover { background-color: #40a9ff; }
            QPushButton:pressed { background-color: #096dd9; })";

        ui->backButton->setStyleSheet(commonButtonStyle);
        ui->dictationButton->setStyleSheet(commonButtonStyle);

        // 单词列表样式
        QString listStyle = R"(
            QListWidget { font-family: "Microsoft YaHei"; font-size: 15px; border: 1px solid #d9d9d9; border-radius: 5px; padding: 5px; min-height: 400px; }
            QListWidget::item { padding: 8px; height: 30px; }
            QListWidget::item:hover { background-color: #f5f5f5; }
            QListWidget::item:selected { background-color: #1890ff; color: #ffffff; })";
        ui->wordsListWidget->setStyleSheet(listStyle);
        ui->wordsListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    }

    void VocabWordsPage::populateWordsList(const QList<Word> &words)
    {
        ui->wordsListWidget->clear();
        if (words.isEmpty()) {
            ui->dictationButton->setEnabled(false);
            QListWidgetItem *emptyItem = new QListWidgetItem("此词库中没有单词");
            emptyItem->setTextAlignment(Qt::AlignCenter);
            emptyItem->setFlags(emptyItem->flags() & ~Qt::ItemIsSelectable);
            ui->wordsListWidget->addItem(emptyItem);
            return;
        }

        ui->dictationButton->setEnabled(true);

        QString downloadButtonStyle = R"(
            QPushButton {
              font-family: "Microsoft YaHei";
              font-size: 12px;
              padding: 5px;
              background-color: #52c41a; /* Green for download */
              color: #ffffff;
              border-radius: 3px;
              border: none;
              min-width: 30px;
            }
            QPushButton:hover { background-color: #73d13d; }
            QPushButton:pressed { background-color: #389e0d; }
            QPushButton[downloaded="true"] {
                background-color: #bfbfbf; /* Grey for downloaded */
                color: #ffffff;
            }
            QPushButton[downloaded="true"]:hover { background-color: #a6a6a6; }
            QPushButton[downloaded="true"]:pressed { background-color: #8c8c8c; }
        )";

        for (const Word &word : words) {
            QWidget *itemWidget = new QWidget();
            QHBoxLayout *layout = new QHBoxLayout(itemWidget);
            layout->setContentsMargins(5, 5, 5, 5);
            layout->setSpacing(10);

            QPushButton *downloadButton = new QPushButton();
            downloadButton->setStyleSheet(downloadButtonStyle);

            bool isDownloaded = LocalWordManager::instance().isWordDownloaded(word.id);
            downloadButton->setText(isDownloaded ? "已下载" : "下载");
            downloadButton->setProperty("downloaded", isDownloaded);

            connect(downloadButton, &QPushButton::clicked, this, [this, word, downloadButton]() {
                handleDownloadButtonClicked(word, downloadButton);
            });

            QLabel *wordLabel = new QLabel(QString("%1 (%2)").arg(word.word).arg(word.meaning));
            wordLabel->setStyleSheet("font-family: 'Microsoft YaHei'; font-size: 14px; background-color: transparent;");
            wordLabel->setWordWrap(true);

            layout->addWidget(downloadButton);
            layout->addWidget(wordLabel, 1);
            itemWidget->setLayout(layout);

            QListWidgetItem *item = new QListWidgetItem(ui->wordsListWidget);
            //item->setSizeHint(itemWidget->sizeHint());
            ui->wordsListWidget->addItem(item);
            ui->wordsListWidget->setItemWidget(item, itemWidget);
        }
    }

    void VocabWordsPage::setupConnections()
    {
        connect(serverhelper, &ServerHelper::getWordsByVocabularyIdFinished, this,
                [this](bool success, int vocabId, const QList<Word> &words, const QString &error) {

                    if (vocabId != vocabulary.id) return;

                    ui->wordsListWidget->clear();
                    wordsForDictation.clear();

                    if (success) {
                        wordsForDictation = words;
                        populateWordsList(words);
                    } else {
                        ui->dictationButton->setEnabled(false);
                        MessageBox::error(this, error.isEmpty() ? "获取单词失败" : error);
                        QListWidgetItem *errorItem = new QListWidgetItem("加载单词失败");
                        errorItem->setTextAlignment(Qt::AlignCenter);
                        ui->wordsListWidget->addItem(errorItem);
                    }
                });

        connect(dictationDialog, &DictationDialog::dictationActionTaken, this,
                [this](DictationDialog::DictationResult result, const Word& dictationWord) {
                    int userId = UserManager::instance().getUserId();
                    if (userId <= 0) {
                        MessageBox::warning(this, "用户未登录，无法记录错题。");
                        return;
                   }

                    switch ((int)result) {
                        case DictationDialog::DictationResult::ConfirmedCorrect:
                            QTimer::singleShot(1000, this, &VocabWordsPage::startNextDictationWord);
                            break;

                        case DictationDialog::DictationResult::ConfirmedWrong:
                            serverhelper->addWordToMistakesBook(userId, dictationWord.id);
                            QTimer::singleShot(1000, this, &VocabWordsPage::startNextDictationWord);
                            break;

                        case DictationDialog::DictationResult::Abandoned:
                            serverhelper->addWordToMistakesBook(userId, dictationWord.id);
                            QTimer::singleShot(1000, this, &VocabWordsPage::startNextDictationWord);
                            break;

                        case DictationDialog::DictationResult::Finished:
                            endDictationSession();
                            break;
                    }
                });

        connect(dictationDialog, &QDialog::rejected, this, &VocabWordsPage::endDictationSession);


        connect(serverhelper, &ServerHelper::addWordToMistakesBookFinished, this,
                 [this](bool success, int wordId, const QString& error){
                     if (dictationDialog && dictationDialog->getCurrentWord().id == wordId) {
                         if (success) {
                             MessageBox::info(dictationDialog, QString("单词 '%1' 已添加到错题本。").arg(dictationDialog->getCurrentWord().word));
                         } else {
                             MessageBox::error(dictationDialog, "添加到错题本失败: " + error);
                         }
                     }
                 });
    }

    void VocabWordsPage::refreshWords()
    {
        if (!UserManager::instance().isLoggedIn())
            return;

        serverhelper->getWordsByVocabularyId(
                    UserManager::instance().getUserId(),
                    vocabulary.id);
    }

    void VocabWordsPage::on_backButton_clicked()
    {
        endDictationSession();
        emit backToStudyPage();
    }

    void VocabWordsPage::on_wordsListWidget_itemClicked(QListWidgetItem *item)
    {
        QString word = item->text();
        emit wordSelected(word);
    }

    void VocabWordsPage::on_dictationButton_clicked()
    {
        if (wordsForDictation.isEmpty()) {
            MessageBox::info(this, "当前词库没有单词可供默写。");
            return;
        }

        dictationQueue = wordsForDictation;

        std::shuffle(dictationQueue.begin(), dictationQueue.end(), *QRandomGenerator::global());

        currentDictationIndex = 0;

        startNextDictationWord();
    }

    void VocabWordsPage::handleDownloadButtonClicked(const Word& word, QPushButton* button)
    {
        qDebug() << "VocabWordsPage: Download button clicked for word -" << word.word;

        if (LocalWordManager::instance().isWordDownloaded(word.id)) {

            if (LocalWordManager::instance().removeWord(word.id)) {
                 MessageBox::info(this, QString("单词 '%1' 已从本地移除。").arg(word.word));

                 button->setText("下载");
                 button->setProperty("downloaded", false);
                 button->setStyleSheet(button->styleSheet());

                 MessageBox::warning(this, QString("从本地移除单词 '%1' 失败。").arg(word.word));
            }
        }
        else {
            if (LocalWordManager::instance().saveWord(word)) {
                MessageBox::info(this, QString("单词 '%1' 已保存到本地。").arg(word.word));

                button->setText("已下载");
                button->setProperty("downloaded", true);
                button->setStyleSheet(button->styleSheet());
            } else {
                MessageBox::error(this, QString("保存单词 '%1' 到本地失败。").arg(word.word));
            }
        }
    }

    void VocabWordsPage::handleWordItemClicked(const Word& word)
    {

        qDebug() << "VocabWordsPage: Word item clicked -" << word.word;
        emit wordSelected(word.word);
    }

    void VocabWordsPage::startNextDictationWord()
    {
        if (dictationQueue.isEmpty()) {
            MessageBox::info(this, "词库默写完毕！");
            endDictationSession();
            return;
        }

        Word currentWordToDictate = dictationQueue.takeFirst();

        if (dictationDialog) {
            dictationDialog->startDictation(currentWordToDictate);
            if (dictationDialog->isHidden()) {
                dictationDialog->open();
            }
        }
    }

    void VocabWordsPage::endDictationSession() {
        if (dictationDialog) {
            dictationDialog->close();
        }
        dictationQueue.clear();
        currentDictationIndex = -1;

        emit dictatingDoneRefreshVocabList();
    }

};
